<template>
  <div class="attractionsBox">
    <div class="top" style="display: flex">
      <el-button
        @click="addEmployee"
        style="margin-right: 20px"
        type="primary"
        :icon="Plus"
      >
        新建
      </el-button>
      <el-input
        :prefix-icon="Search"
        style="width: 240px"
        placeholder="查询单个员工"
        v-model="phone"
        @keyup.enter="searchSingleEmploy"
      >
      </el-input>
      <el-button @click="searchSingleEmploy" style="margin-right: 20px" type="primary"
        >搜索</el-button
      >

      <el-select
        v-model="statusValue"
        placeholder="选择状态"
        size="large"
        style="width: 200px"
        @change="getAllEmployee"
      >
        <el-option label="正常" :value="1"> </el-option>
        <el-option label="已禁用" :value="0"> </el-option>
      </el-select>
    </div>
    <div class="bottom">
      <el-table :data="tableData" size="large" style="width: 100%">
        <el-table-column label="id" prop="id" />

        <el-table-column label="用户名" prop="username"></el-table-column>

        <el-table-column label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="danger"> 已停用 </el-tag>
            <el-tag v-else type="success"> 正常 </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="230px">
          <template #default="scope">
            <el-button
              size="large"
              type="primary"
              :icon="Edit"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="
                userStore.getUser() !== null && userStore.getUser().roles === 'ROLE_ADMIN'
              "
            >
              编辑
            </el-button>
            <el-button
              size="large"
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          prev-text="上一页"
          next-text="下一页"
          @prev-click="minusPages"
          @next-click="addPages"
          @current-change="changeCurrent"
          :current-page="pageData.current"
          layout="prev, pager, next"
          :total="pageData.totalPage"
          page-count="5"
        />
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
    <el-form
      :model="form"
      label-position="left"
      :rules="rules"
      style="padding-right: 30px; padding-left: 20px"
    >
      <!-- <el-form-item label="id:" label-width="80" prop="id">
        <el-input v-model="form.id" autocomplete="off" />
      </el-form-item> -->
      <el-form-item label="用户名:" label-width="80" prop="username">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码:" label-width="80" prop="password">
        <el-input v-model="form.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="身份:" label-width="80" prop="roles">
        <el-select v-model="form.roles" placeholder="设置身份">
          <el-option label="管理员" value="ROLE_ADMIN" />
          <el-option label="员工" value="ROLE_EMPLOYEE" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" label-width="80" prop="status">
        <el-select v-model="form.status" placeholder="设置状态">
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="choose"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, reactive } from "vue";
import { Plus, Edit, Delete, Search } from "@element-plus/icons-vue";
import {
  deleteEmployeeAPI,
  pageSearchEmployeeAPI,
  searchSingleEmployeeAPI,
  updateEmployeeAPI,
} from "../../apis/employee";
import { ElMessage } from "element-plus";
import { registerEmployeeAPI } from "../../apis/admin";
import { useUserStore } from "../../stores/userStore";
import { useRouter } from "vue-router";

const router = useRouter();
const userStore = useUserStore();
const phone = ref("");

const dialogFormVisible = ref(false);

const dialogTitle = ref("新增账号");

const choose = () => {
  if (dialogTitle.value === "新增账号") {
    createEmployee();
  } else {
    editEmployee();
  }

  dialogFormVisible.value = false;
};

const addEmployee = () => {
  dialogTitle.value = "新增账号";
  dialogFormVisible.value = true;

  form.value = {
    id: "",
    username: "",
    password: "",
    roles: "",
    status: 1,
  };
};

const form = ref<Employee>({
  id: "",
  username: "",
  password: "",
  roles: "",
  status: 1,
});

const statusValue = ref(1);

interface Employee {
  id: string;
  password: string;
  roles: string;
  status: number;
  username: string;
}

const search = ref("");

const handleEdit = (index: number, row: Employee) => {
  dialogTitle.value = "编辑账号";

  form.value = JSON.parse(JSON.stringify(row));

  dialogFormVisible.value = true;
};

const handleDelete = async (index: number, row: Employee) => {
  let flag = confirm("你确定要删除吗");

  if (flag == true) {
    const res = await deleteEmployeeAPI(row.username);

    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      getAllEmployee()
    } else ElMessage.error("删除失败");
  }
};

const editEmployee = async () => {
  const res = await updateEmployeeAPI(
    form.value.id,
    form.value.username,
    form.value.password,
    form.value.roles,
    form.value.status
  );

  if (res.data.code === "200") {
    ElMessage.success("修改成功");
    getAllEmployee();
  } else ElMessage.error("修改失败");
};

const createEmployee = async () => {
  const res = await registerEmployeeAPI(
    form.value.id,
    form.value.username,
    form.value.password,
    form.value.roles,
    form.value.status
  );

  if (res.data.code === "200") {
    ElMessage.success("新建成功");
    getAllEmployee()
  } else {
    ElMessage.error("创建失败");
  }
};

const pageData = ref({
  current: 1,
  totalPage: 1,
});

const changeCurrent = (number) => {
  pageData.value.current = number;
  getAllEmployee();
};

const addPages = () => {
  getAllEmployee();
};

const minusPages = () => {
  getAllEmployee();
};

const tableData = ref<Employee[]>([
  {
    id: "1",
    username: "12",
    password: "123",
    roles: "employee",
    status: 1,
  },
]);

const getAllEmployee = async () => {
  const res = await pageSearchEmployeeAPI(1, 5, statusValue.value);

  if (res.data.code === "200") {
    console.log(res.data.data);
    tableData.value = res.data.data.data;
    pageData.value.totalPage = res.data.data.total;
    // tableData.value=res.data.data
  } else ElMessage.error(res.data.message);
};

const searchSingleEmploy = async () => {
  if (phone.value.trim() === "") {
    getAllEmployee();
    return;
  }

  const res = await searchSingleEmployeeAPI(parseInt(phone.value.trim()));

  if (res.data.code === "200") {
    tableData.value = [res.data.data];
  } else ElMessage.error("搜索失败");
};

const rules = reactive({
  id: [{ required: true, message: "请输入id", trigger: "change" }],
  username: [{ required: true, message: "请输入名字", trigger: "change" }],
  password: [{ required: true, message: "请输入密码", trigger: "change" }],
  roles: [{ required: true, message: "请选择", trigger: "change" }],
  status: [{ required: true, message: "请选择", trigger: "change" }],
});

onMounted(() => {
  getAllEmployee();

  if (userStore.getUser() === null) router.push("/login");
});
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
